﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using Home.MobileSales.Common.Models;

namespace Home.MobileSales.ImpExpData.Core
{
    public class ExportVisitsByDate:ExportVisits
    {
        public DateTime BeginDate{ get; set;}
        public DateTime EndDate { get; set;}
        public bool Repeat { get; set; }



        public override void Execute()
        {
            try
            {
                visits =Repeat?DataManager.GetInstance().Visists.GetVisitsByDate(BeginDate, EndDate, true):
                    DataManager.GetInstance().Visists.GetVisitsByDate(BeginDate, EndDate, true).Where(v=>v.IsReadOnly == false).ToList();

                xml = XmlWriter.Create(FileName.FullName);
                xml.WriteStartDocument();
                xml.WriteStartElement("Visits");
                xml.WriteStartAttribute("BeginDate");
                xml.WriteValue(this.BeginDate);
                xml.WriteEndAttribute();
                xml.WriteStartAttribute("EndDate");
                xml.WriteValue(this.EndDate);
                xml.WriteEndAttribute();
                ExportVisit();
                xml.WriteEndElement();
                xml.WriteEndDocument();
                foreach (var visit in visits)
                {
                    if (!visit.IsReadOnly)
                    {
                        visit.IsReadOnly = true;
                        DataManager.GetInstance().Visists.UpdateVisit(visit);
                    }
                    foreach (var order in visit.Orders.Where(order => !order.IsReadOnly))
                    {
                        order.IsReadOnly = true;
                        DataManager.GetInstance().Orders.UpdateOrder(order);
                    }
                }
            }
            finally
            {
                if (xml != null)
                {
                    xml.Close();
                }
            }
        }
    }
}
